//
//  QRCodeViewController.swift
//  LongTermInsurance
//
//  Created by DYD on 2019/1/10.
//  Copyright © 2019 HeChao. All rights reserved.
//

import UIKit
import CoreImage

class QRCodeViewController: UIViewController {

    lazy var qrImageView: UIImageView = {
        let imageView = UIImageView(frame: CGRect.zero)
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    lazy var dataString = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "二维码"
        // Do any additional setup after loading the view.
        view.addSubview(qrImageView)
        qrImageView.snp.remakeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalToSuperview().offset(-40)
            make.height.equalTo(view.snp.width).offset(-40)
        }
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closePage))
        
        refrshRQCode()
    }
    
    @objc func closePage() {
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    
    func refrshRQCode() {
        qrImageView.image = nil
        if dataString.count == 0 {
            return
        }
        if let filter = CIFilter(name: "CIQRCodeGenerator") {
            filter.setDefaults()
            let data = dataString.data(using: String.Encoding.utf8, allowLossyConversion: true)
            filter.setValue(data, forKey: "inputMessage")
            if let ciImage = filter.outputImage {
                let image = generateImage(ciImage: ciImage, size: (DeviceInfo.screenWidth - 40.0))
                self.qrImageView.image = image
            }
        }
    }
    
    func generateImage(ciImage: CIImage, size: CGFloat) -> UIImage {
        
        let integral = ciImage.extent.integral
        let scale = min(size / integral.width, size / integral.height)
        let width = integral.width * scale
        let height = integral.height * scale
        let colorSpace = CGColorSpaceCreateDeviceGray() //CGColorSpaceCreateDeviceGray
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(ciImage, from: integral)!
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: scale, y: scale)
        bitmapRef.draw(bitmapImage, in: integral);
        let cgImage: CGImage = bitmapRef.makeImage()!
        let image = UIImage(cgImage: cgImage)
        return image
    }

}
